<?php

class SF_Ulmartlogin_LoginController extends Mage_Core_Controller_Front_Action 
{
	protected $email;
	protected $redirectUrl;		//跳转URL

	public function AuthorizationAction()
	{
		$_host = 'http://127.0.0.1:8080/rumall/services/rumallInterService?wsdl';
		$act = $this->getRequest()->getParam('act');
		switch ($act) {
			case 'customer':
				$this->redirectUrl = 'customer/account/login';
				break;
			
			case 'checkout':
				$this->redirectUrl = 'checkout/onepage/index';
				break;
		}

		$this->email = $_POST['login']['username'];
		$password = $_POST['login']['password'];
		$soap = new SoapClient($_host);
		$result = $soap->getCrossBordAuthr($this->email, $password);

		Mage::log('ulmart用户登陆');
		Mage::log($this->email);
		Mage::log($result);
		if(substr($result,0,1) == '1')
		{

			//查询是否已存在cust_id,不存在则新增
			$read = Mage::getSingleton('core/resource')->getConnection('core_read')
					->fetchAll("select count(id) as user from rumall_ulmart_user where ulmart_user = '". $this->email ."'");
			if($read[0]['user'] == 0)
			{
				$write = Mage::getSingleton('core/resource')->getConnection('core_write');  
				$write->query("insert into rumall_ulmart_user (ulmart_user,ulmart_custid) VALUES ('{$this->email}','". substr($result,strpos($result,'_')+1) ."')");
				
			} 
			
			$this->ulmartAction();

		}
		else
		{
			Mage::getSingleton('core/session')->addError('Invalid login or password.');
			$this->_redirectUrl(Mage::getUrl($this->redirectUrl));
		}
	}

	public function ulmartAction(){
		$password = 'fas4f!sadf_Sa';
		$firstname = mb_substr($this->email, 0, mb_strpos($this->email,'@',1,'utf-8'), 'utf-8');
		$customer = Mage::getModel('customer/customer');
		$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
		$customer->loadByEmail($this->email);
		


		//检查用户是否已存在，不存在则创建并自动登录。存在则自动登录
		if(!$customer->getId()) 
		{
			
			$customer->setEmail($this->email);
			$customer->setGroupId('4'); //Ulmart group
			$customer->setFirstname($firstname);
			$customer->setLastname(null);
			$customer->setPassword($password);
			$customer->setConfirmation(null);
			$customer->save();

			try {
				Mage::getSingleton('customer/session')->loginById($customer->getId());
				$this->_redirectUrl(Mage::getUrl($this->redirectUrl));
			} catch (Exception $e) {
				echo $e->getMessage();
			}

		} 
		else 
		{
			
		    try 
		    {
		        $session = Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer);
		        $this->_redirectUrl(Mage::getUrl($this->redirectUrl));
		    } 
		    catch(Exception $e) 
		    {
		    	Mage::getSingleton('core/session')->addError('Login false.');
		    	$this->_redirectUrl(Mage::getUrl($this->redirectUrl));
		    }
		}
	}


}